﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CodeBuilder2.BLL.Schema;
using System.Threading;
using CodeBuilder2.BLL.CodeGenerateor;
using System.Data;
using CodeBuilder2.BLL;
using System.CodeDom.Compiler;
using CodeBuilder2.BLL.Connection;

namespace CodeBuilder2.View.CB_UserControl.Content
{
    /// <summary>
    /// TableSelectContent.xaml 的交互逻辑
    /// </summary>
    public partial class TableSelectContent : UserControl
    {
        DataBaseBLL dbBll = new DataBaseBLL();
        public string ServerName { get; set; }
        public string DataBaseName { get; set; }

        public TableSelectContent()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            ConnectionHelper.ChangeDataBase(ServerName, DataBaseName);
            // 加载所选库的所有表名
            List<string> names = dbBll.GetTablesName(ServerName, DataBaseName);
            names.Sort();
            foreach (var item in names)
            {
                CheckBox chk = new CheckBox();
                chk.Content = item.Replace("_", "__");
                spChkContainer.Children.Add(chk);
            }
            //var allName = from name in names
            //              select new { table_name = name };
            //lstChkContainer.ItemsSource = allName;
        }

        string nameSpace;
        CodeDomProvider cdp = null;
        private void btnBuild_Click(object sender, RoutedEventArgs e)
        {
            nameSpace = txtNameSpace.Text;
            if (nameSpace == "Model")
            {
                MessageBoxResult result = MessageBox.Show("您确定使用默认的\"Model\"作为您的实体类的命名空间吗？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Information);
                if (result == MessageBoxResult.No)
                    return;
            }

            var tableNames = from CheckBox item in spChkContainer.Children
                             where item.IsChecked == true
                             select item.Content.ToString();
            List<string> tns = tableNames.ToList();

            ThreadStart start = delegate()
            {
                this.DisplayCode(tns);
            };


            switch ((cbxLanguageName.SelectedItem as ComboBoxItem).Content.ToString())
            {
                case "CSharp":
                    cdp = CodeDomProvider.CreateProvider("CSharp");
                    break;
                case "Visual Basic":
                    cdp = CodeDomProvider.CreateProvider("VisualBasic");
                    break;
                case "JScript":
                    cdp = CodeDomProvider.CreateProvider("JScript");
                    break;
                default:
                    cdp = CodeDomProvider.CreateProvider("CSharp");
                    break;
            }

            Thread t = new Thread(start);
            t.Start();

            ThreadStart start2 = delegate()
            {
                if (mw.tcMain.Items.Count > 0)
                {
                    TabItem tab = (mw.tcMain.Items[0] as TabItem);
                    tab.IsSelected = true;
                    //tab.Visibility = Visibility.Visible;
                }
            };
            mw.Dispatcher.BeginInvoke(start2);

            // 关闭当前用户控件所在的窗口
            App.SimpleFloatWindow.Close();

            //MessageBox.Show(chks.Count().ToString());

            //var lst = from ListBoxItem item in lstChkContainer.Items
            //          where (item.Content as CheckBox).IsChecked == true
            //          select item;
            //int count = lst.Count();
            //foreach (var item in lst)
            //{
            //    FrameworkElement fe = lstChkContainer.ItemContainerGenerator.ContainerFromItem(item) as FrameworkElement;
            //    FrameworkElement cp = VisualTreeHelper.GetChild(fe, 0) as FrameworkElement;
            //    object o=lstChkContainer.ItemTemplate.FindName("chkTable", cp);
            //}
        }

        //List<string> tns;

        MainWnd mw = App.MainWnd;
        void DisplayCode(List<string> tns)
        {
            EntityGenerator eg = new EntityGenerator();
            BuilderBaiscServices bbs = new BuilderBaiscServices();
            DataSet ds = null;

            //IEnumerable<string> names = tns as IEnumerable<string>;

            foreach (var item in tns)
            {
                string tableName = item.Replace("__", "_");
                ds = bbs.GetColumns(tableName);
                eg.ClassName = tableName;
                eg.FieldTableInfo = ds.Tables[0];
                eg.NameSpace = nameSpace;

                #region 确保 using 块不被输出到 namespace 块内部
                string code = eg.GenerateCode(cdp).Replace("\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Text;\r\n", "");
                code = code.Replace("\r\nnamespace", "\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\n\r\nnamespace");
                #endregion

                // 为了格式良好的大括号后的换行（连换两个行是不好的）
                code = code.Replace("{    \r\n    \r\n", "{\r\n").Replace("{\r\n        \r\n", "{\r\n");

                ParameterizedThreadStart pStart = delegate(object tabInfo)
                {
                    Infos info = (Infos)tabInfo;
                    TabItem tab = new TabItem();
                    tab.Header = info.tabHeader;

                    TextBox txt = new TextBox();
                    txt.AcceptsReturn = true;
                    txt.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
                    txt.Text = info.codeContent;

                    tab.Content = txt;

                    mw.tcMain.Items.Add(tab);
                };
                Infos infos = new Infos();
                infos.tabHeader = item;
                infos.codeContent = code;
                mw.Dispatcher.BeginInvoke(pStart, System.Windows.Threading.DispatcherPriority.Normal, infos);
            }
        }
        class Infos
        {
            internal string tabHeader;
            internal string codeContent;
        }
        void BuildCode()
        {
        }
    }
}
